// pages/index/createOrder/createOrder.js
var app = getApp();
import Api from '../../../api/api.js';
const api = new Api();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    dataList:[],
    totalPrice:"0",
    totalFee:"0",
    adressDict:null,
    isHaveAddress:false,
    postId:null,
    orderType:'',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.postId){
      this.data.postId = options.postId;
    }
    this.setData({
      orderType: app.ORDER_TYPE
    });
    var stringList = wx.getStorageSync("payList");
    var list = JSON.parse(stringList);
    this.setData({
      dataList: list
    });
    this.getTotalPrice();
    if (this.data.orderType == 5) {
      this.getAdressData();
    }
  },
  getTotalPrice(){
    var list = this.data.dataList;
    var totalPrice = 0;
    for(var i = 0;i < list.length;i++){
      var dict = list[i];
      var count = parseInt(dict.selectCount + "");
      var pirce = parseFloat(dict.salePrice + "");
      totalPrice += count * pirce;
    }
    console.log("totalPrice====",totalPrice);
    this.setData({
      totalPrice: totalPrice+""
    });
  },
  beginPayOrder() {
    if (this.data.orderType == 1 || this.data.orderType == 5) {
        if (this.data.adressDict == null) {
          app.alert("请选择地址~");
          return;
        }
      }
   
    var _this = this;
    var map = {};
    if (this.data.postId){
      map.contentId = this.data.postId;
    }
    if (this.data.orderType == 1 || this.data.orderType == 5) {
      map.address = this.data.adressDict.address;
      map.city = this.data.adressDict.city;
      map.mobile = this.data.adressDict.mobile;
      map.userName = this.data.adressDict.name;
    }
    map.amount = this.data.totalPrice
    map.fee = this.data.totalFee;
    map.formId = "1";
    map.message = "333";
    map.openId = app.OPEN_ID();
    map.appId = app.APP_ID;
    map.orderType = app.ORDER_TYPE;
    if (app.ORDER_TYPE == "6"){
      map.basesId = app.BASE_ID;
    }
    map.userId = app.USER_ID();
    var list = [];
    for (var i = 0; i < this.data.dataList.length; i++) {
      var dic = this.data.dataList[i];
      var data = {};
      data.productId = dic.productId;
      data.contentId = dic.contentId;
      data.qty = dic.selectCount;
      data.skuId = dic.skuId;
      list.push(data);
    }
    map.childSaveParamList = list;
    console.log("map=======",JSON.stringify(map));
    api.getRequestData(app.createOrderUrl, map, true, "POST").then(res => {
      if (res.data.errorCode == 0) {
        var orderId = res.data.model;
        _this.payOrder(orderId);
      } else {
        app.alert(res.data.errorMsg)
      }
    });
  },

  payOrder(orderId) {
    var _this = this;
    var map = {};
    map.orderId = orderId;
    map.appId = app.APP_ID;
    map.userId = app.USER_ID();
    map.openId = app.OPEN_ID();
    api.getRequestData(app.payOrderUrl, map, false,"POST").then(res => {
      if (res.data.errorCode == 0) {
        var dict = res.data.model.wxPayMpOrderResult;
        _this.beginPay(dict, orderId);
      } else {
        app.alert(res.data.errorMsg);
      }
    }).catch(err => {
    });
  },
  beginPay: function (data, orderId) {
    var _this = this;
    wx.requestPayment({
      timeStamp: data.timeStamp,
      nonceStr: data.nonceStr,
      package: data.packageValue,
      signType: data.signType,
      paySign: data.paySign,
      success: function (res) {
        wx.showToast({
          title: "支付成功",
          icon: 'success',
          mask: true,
          duration: 1500
        });
        setTimeout(() => {
          wx.navigateBack({
            delta:2,
          })
        }, 1400);
      },
      fail: function (res) {
        app.alert("支付失败");
        setTimeout(() => {
          wx.navigateBack({
            delta:2,
          })
        }, 1400);
      },
      complete: function (res) {

      }
    })
  },
 
  getAdressData(){
    var _this = this;
    var map = {};
    map.appId = app.APP_ID;
    map.userId = app.USER_ID();;
    map.openId = app.OPEN_ID();

    api.getRequestData(app.mineAdressList, map, false, "POST").then(res => {
      if (res.data.errorCode == 0) {
        var list = res.data.model;
        if (list.length == 0) {
          _this.setData({
            isHaveAddress:false
          });
        } else {
          _this.setData({
            isHaveAddress: true
          });
          var dict = null;
          for (var index in list){
            var dic = list[index];
            if (dic.isDefault == 1) {
              dict = dic;
            }
          }
          if (dict == null) {
            dict = list[0];
          }
          _this.setData({
            adressDict: dict
          });
          _this.getFeeData();

        }
    
      } else {
        app.alert(res.data.errorMsg);
      }
    });
  },
  goToChooseAddress(){
    wx.navigateTo({
      url: '/pages/mine/address/address?type=selectAdd',
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (this.data.adressDict) {
      this.getFeeData();
    }
  },
  getFeeData(){
    var city = this.data.adressDict.city;
    var list = this.data.dataList;
    city = city.substring(0,2);
    console.log(city);
    var needPayFee = false;
    for (var i = 0; i < list.length; i++) {
      var dict = list[i];
      var note = dict.note;
      console.log("note=======",note);
      if (note){
        var index = note.indexOf(city);
        if (index != -1) {
          needPayFee = true;
          break;
        }
      }
    }
    if (needPayFee) {
      this.setData({
        totalFee: 10,
      });
    } else {
      this.setData({
        totalFee: 0,
      });
    }
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})